package com.tvunetworks.center.device.util;

import com.tvunetworks.center.common.model.dto.CheckAuthDTO;
import com.tvunetworks.center.common.util.HttpUtil;
import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.MyUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.device.service.feign.AccessFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Ethan
 * @program:
 * @description:
 * @create: 2022/4/27 16:05
 **/
@Component
@Slf4j
public class AnywhereAuthUtil {


    @Autowired
    private AccessFeignService accessFeignService;

    /**
     *  对手机端传过来的Appkey和Secret进行校验
     * @param request request
     * @param requestdata 数据
     * @return 是否有权限
     */
    public boolean anyWhereAuth(HttpServletRequest request,String requestdata) {

        com.alibaba.fastjson.JSONObject requestObject = com.alibaba.fastjson.JSONObject.parseObject(requestdata);
        String appkey = requestObject.getString("appkey");
        String signature = requestObject.getString("signature");
        String timestamp = requestObject.getString("timestamp");


        CheckAuthDTO checkAuthDTO = new CheckAuthDTO();
        checkAuthDTO.setAppkey(appkey);
        checkAuthDTO.setSignature(signature);
        checkAuthDTO.setTimestamp(timestamp);
        String ip = HttpUtil.getClientPublicIP(request);
        checkAuthDTO.setIp(ip);
        checkAuthDTO.setFunction("default");
        checkAuthDTO.setRequestId(MyUtil.getUUID());

        Result<Void> checkAuthResult = accessFeignService.checkAuth(checkAuthDTO);
        if (checkAuthResult.assertSuccess()) {
            return true;
        } else {
            try {
              String  result = JsonUtil.toJsonStr(checkAuthResult);
                log.error("[the anywhereAuth is failed ,resule : [{}]" , result);
            } catch (Exception e) {
                log.error("the checkAuthResult Exception ,e : [{}]" ,e);
            }
            return false;
        }
    }


}
